/**
 *
 * @author John Creecy
 */
package battlebarnchat;

import java.io.IOException;
import java.net.*;

public class ChatListener implements Runnable {

	public ChatListener() {
	}

	public void run() {
		socketMonitor();
	}

	public void socketMonitor() {
		String packetData = "";
		String packetMessage = "";
		String chatMessages = "";
		long packetTimeStamp = 0;

		while (true) {
			try {
				DatagramSocket serverSocket = new DatagramSocket(9999);
				while (true) {
					byte[] receiveData = new byte[1024];
					try {
						DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
						serverSocket.receive(receivePacket);
						packetData = new String(receivePacket.getData());
						InetAddress sourceIp = receivePacket.getAddress();

						packetTimeStamp = Long.parseLong(packetData.substring(0, 12));
						packetMessage = packetData.substring(13);
						if (packetTimeStamp > Main.lastPacketTime) {
							chatMessages = chatMessages + packetMessage + "\n";
							Main.lastPacketTime = packetTimeStamp;
						}

					} catch (SocketException ex) {
						System.out.println(ex);
					} catch (IOException ex) {
						System.out.println(ex);
					}

					Main.statusMessage.setText(chatMessages);
				}
			} catch (SocketException ex) {
				System.out.println(ex);
			}
		}
	}
}
